package homework1_3;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import java.util.Scanner;

/**
 * 服务器通信线程类
 */
public class ServerThread extends Thread{
    private List<Socket> sockets;
    private BufferedReader br;

    private Socket s;
    public ServerThread(List<Socket> sockets,Socket s){
        this.sockets = sockets;
        this.s = s;
    }
    @Override
    public void run() {


        try {
            br = new BufferedReader(new InputStreamReader(s.getInputStream()));//获取输入流接收数据

            while (true){
                String str = br.readLine();//接收客户端发来的字符串
                System.out.println(str);
                String[] strings = str.split(":");
                System.out.println("客户端"+strings[0]+"发来了："+strings[1]);
                for (Socket socket:sockets
                ) {
                    boolean flag = false;
                    try {
                        flag = socket.getKeepAlive();
                    }catch (Exception e){
                        continue;
                    }

                    if (!flag){
                        PrintStream ps = new PrintStream(socket.getOutputStream());//获取输出流回发数据
                        ps.println(str);
                        ps.flush();

                    }

                }
                System.out.println("已将发来的数据"+str+"转发给其他客户端!");

                if ("bye".equals(strings[1])){
                    System.out.println("客户端"+s.getInetAddress()+"已下线");
                    break;
                }

            }

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(null != s){
                try {
                    s.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null!=br){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

